import { ref } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";

function formSetting(changeFn, addRequest, editRequest) {
    const type = ref('add')
    const editVisible = ref(false)
    const btnLoading = ref(false)
    const ruleFormRef = ref()
    let form = ref({})
    //新建
    function addItem() {
        editVisible.value = true;
        type.value = 'add';
    }
    //编辑弹框
    function handleEdit(index, row) {
        editVisible.value = true;
        type.value = 'edit';
        form.value = JSON.parse(JSON.stringify(row))
    }
    function submitForm(formEl) {
        if (!formEl) return
        formEl.validate((valid) => {
            if (valid) {
                btnLoading.value = true;
                let request = addRequest
                if (type.value != 'add') request = editRequest;
                request(form.value)
                    .then((res) => {
                        if (res.code == 0) {
                            editVisible.value = false;
                            changeFn();
                            ElMessage.success("操作成功");
                        } else {
                            ElMessage.error(res.message);
                        }
                    })
                    .finally(() => {
                        btnLoading.value = false;
                    });
            }
        })
    }
    function resetForm(formEl) {
        if (!formEl) return
        formEl.resetFields();
        form.value = {}
    }

    return {
        type,
        editVisible,
        btnLoading,
        ruleFormRef,
        form,
        addItem,
        handleEdit,
        submitForm,
        resetForm,
    };
}
export default formSetting;